<script setup lang="ts">
import { h, onActivated, onDeactivated, onMounted, onUnmounted, ref } from 'vue';
import { AlertCircle, CheckmarkCircleSharp } from '@vicons/ionicons5';
import { saveAs } from 'file-saver';
import * as htmlDocx from 'html-docx-js-typescript';
import { useAppStore } from '@/store/modules/app';
import { useRouterPush } from '@/hooks/common/router';
import '@/assets/js/flexible';
import { NButton, NIcon, NSpace, NSpin, useDialog, useMessage, useNotification } from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';
import {
  cancelTaskGenerateAction,
  deleteBid,
  getAllFolder,
  getBidTipsAction,
  getFinishedBid,
  getTenantInfo,
  getUsedCount,
  historyWriteListAction
} from '@/service/api';
import { localStg } from '@/utils/storage';
import { USER_INFO } from '@/utils/const';
import { successMessage } from '@/utils/utils';

interface Song {
  no: number;
  title: string;
  length: string;
  status?: number;
}
const dialog = useDialog();

const tableData = ref([]);

const pageCount = ref<number>();

const bidTotal = ref<number>();

const message = useMessage();

const appStore = useAppStore();

const { routerPushByKey } = useRouterPush();

const userInfo = localStg.get(USER_INFO);

const statusObj = ref({
  0: '生成中',
  1: '生成完成',
  2: '生成失败'
});

const bidObj = ref({
  0: '陪标',
  1: '标书'
});

const companyTotal = ref(0);

// 获取维护公司数
async function getAllFolderList() {
  const params: any = { parentId: 0, pageNum: 1, pageSize: 999 };
  const { data, error } = await getAllFolder(params);
  if (!error) {
    companyTotal.value = data.total;
  }
}

const usedCount = ref(0);

// 获取使用剩余数
async function getUsedCountNumber() {
  const params: any = {
    moduleId: localStg.get('moduleId') || 1,
    applicationId: 1
  };
  const { data, error } = await getUsedCount(params);
  if (!error) {
    usedCount.value = data;
    // 判断有无次数
    if (usedCount.value === 0) {
      dialog.info({
        title: '剩余次数不足提醒',
        content: '小主，您已经没有剩余次数了哦~',
        positiveText: '确 定',
        onPositiveClick: () => {}
      });
    }
  }
}

const finishedBid = ref(0);
// 获取生成公司数
async function finishedBidNumber() {
  const params: any = { catalogStatus: 1 };
  const { data, error } = await getFinishedBid(params);
  if (!error) {
    finishedBid.value = data;
  }
}

const userIdentity = ref(0);

const expireDate = ref('');

// 获取生成公司数
async function getUserIdentity() {
  const { data, error } = await getTenantInfo();
  if (!error) {
    userIdentity.value = data.status;
    const parts = data.expireTime.split('-');
    expireDate.value = `${parts[0]} 年 ${parts[1]} 月 ${parts[2]} 日`;
  }
}

// 删除任务 取消排队
function handleDelete(row: any) {
  dialog.info({
    title: '删除标书',
    content: '请问是否确认删除该标书？',
    positiveText: '确定',
    negativeText: '返回',
    onPositiveClick: async () => {
      const { data, error } = await deleteBid(row.id);
      // 算法取消排队接口
      if (row.status == 0) {
        await cancelTaskGenerateAction({
          task_id: row.id
        });
      }
      if (!error) {
        message.success('已删除');
        await getTableList();
      }
    },
    onNegativeClick: () => {
      message.warning('已取消');
    }
  });
}

const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;

const otherUrl: any = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

const imgUrl = otherUrl.imgUrl;

// 下载标书
function downloadBid(row: any) {
  const fileStr = row.filePath;
  if (fileStr.includes('.docx')) {
    saveAs(imgUrl + fileStr, `${row.title}.docx`, { encoding: 'UTF-8' });
    successMessage('文档下载成功');
  } else {
    let htmlContentStr: string = row.filePath;

    htmlContentStr = htmlContentStr.replace(/<img /g, '<img width="650" height="650"');
    // 设置表格边框
    const htmlContent = htmlContentStr.replaceAll(/<table/g, `<table border-collapse="collapse" border="1" `);

    const formatContent = `
    	 	<!DOCTYPE html>
    	 	<html lang="en">
          <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>${row.title}</title>
          </head>
          <body>
             ${htmlContent}
          </body>
        </html>`;

    const convertedFile = htmlDocx.asBlob(formatContent);

    // 生成链接并且下载
    convertedFile.then(fileData => {
      saveAs(fileData as Blob, `${row.title}.docx`, { encoding: 'UTF-8' });
      successMessage('文档下载成功');
    });
  }
}

// 编辑
function handleEdit(row: any) {
  const pushParams: any = {
    generateType: 1,
    taskId: row.id,
    fileName: row.title
  };
  routerPushByKey('document_detail', { query: pushParams });
}

function createColumns({ play }: { play: (row: Song) => void }): DataTableColumns<Song> {
  return [
    {
      title: '序号',
      align: 'center',
      key: 'key',
      render: (_, index) => {
        return `${(formData.value.pageNum - 1) * formData.value.pageSize + index + 1}`;
      }
    },
    {
      title: '项目名称',
      key: 'title',
      align: 'center',
      width: '200px',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '类型',
      key: 'type',
      align: 'center',
      render(row: any) {
        return bidObj.value[row.type];
      }
    },
    {
      title: '状态',
      key: 'status',
      align: 'center',
      render(row: any) {
        if (row.status == 0) {
          return [h(NSpin, {}, { default: () => '生成中' })];
        } else if (row.status == 1) {
          return [
            h(
              'div',
              {
                class: 'flex justify-center'
              },
              [
                h(
                  NIcon,
                  { color: '#68BF7B', size: '22px' },
                  {
                    default: () => h(CheckmarkCircleSharp)
                  }
                ),
                h('span', { class: 'ml-3px' }, ['已完成'])
              ]
            )
          ];
        }
        return [
          h(
            'div',
            {
              class: 'flex justify-center'
            },
            [
              h(
                NIcon,
                { color: '#FF7575', size: '22px' },
                {
                  default: () => h(AlertCircle)
                }
              ),
              h('span', { class: 'ml-3px' }, ['生成失败'])
            ]
          )
        ];
      }
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      width: '300px',
      render(row) {
        if (row.status == 1) {
          return [
            h(
              NButton,
              {
                type: 'info',
                strong: true,
                tertiary: true,
                style: 'margin:0 5px',
                onClick: () => handleEdit(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NButton,
              {
                type: 'success',
                strong: true,
                tertiary: true,
                style: 'margin:0 5px',
                onClick: () => downloadBid(row)
              },
              { default: () => '下载' }
            ),
            h(
              NButton,
              {
                type: 'error',
                strong: true,
                tertiary: true,
                style: 'margin:0 5px',
                onClick: () => handleDelete(row)
              },
              { default: () => '删除' }
            )
          ];
        }
        return [
          h(
            NButton,
            {
              type: 'error',
              strong: true,
              tertiary: true,
              style: 'margin:0 5px',
              onClick: () => handleDelete(row)
            },
            { default: () => '删除' }
          )
        ];
      }
    }
  ];
}

const columns: any = createColumns({
  play(row: Song) {
    message.info(`Play ${row.title}`);
  }
});

// 跳转立即智写
function createDocumentClick() {
  if (usedCount.value == 0) {
    return;
  }
  const params: any = {
    remainTimes: usedCount.value
  };
  routerPushByKey('document_create', { query: params });
}

// 标书素材资产
function bidMaterialsClick() {
  routerPushByKey('bid-materials');
}

const searchValue = ref<string>('');

const tableLoading = ref(false);

// 每五秒刷新一次列表
// const timer = window.setInterval(() => {
//   getTableList();
// }, 5000);

// 卸载定时器
onUnmounted(() => {
  // clearInterval(timer);
});

async function getTableList() {
  // 当加载时不重复调用接口
  if (!tableLoading.value) {
    tableLoading.value = true;
    const { data, error } = await historyWriteListAction(formData.value);
    if (!error) {
      tableData.value = data?.records;
      pageCount.value = data?.pages;
      bidTotal.value = data?.total;
      tableLoading.value = false;
    }
  }
}

interface FormType {
  pageNum: number;
  pageSize: number;
  userId?: any;
}
const formData = ref<FormType>({
  pageNum: 1,
  pageSize: 6,
  userId: userInfo?.userId
});

onMounted(() => {
  // getTableList();
  getAllFolderList();
  finishedBidNumber();
  getUsedCountNumber();
  getUserIdentity();
});

const finishTimer = ref(null);

onActivated(() => {
  queryFinishedBidDocument();

  finishTimer.value = setInterval(() => {
    queryFinishedBidDocument();
  }, 20000);
});

onDeactivated(() => {
  if (finishTimer.value) {
    clearInterval(finishTimer.value);
    finishTimer.value = null;
  }
});

const notification = useNotification();

// 查询是否有新生成的标书
async function queryFinishedBidDocument() {
  const { data, error } = await getBidTipsAction();
  if (!error && data !== undefined && data && data.id) {
    const bidNotification = notification.create({
      content: '小主，你有一份标书撰写完成！',
      duration: 10000,
      closable: false,
      action: () =>
        h(
          NSpace,
          { justify: 'end' },
          {
            default: () => [
              h(
                NButton,
                {
                  // 可在里面写按钮样式
                  type: 'tertiary',
                  size: 'small',
                  style:
                    'height: 32px; font-family: HarmonyOS Sans SC; background: #CECECE; font-size: 14px; color: #FFFFFF;',
                  onClick: () => {
                    bidNotification.destroy();
                  } // 点击按钮后的回调
                },
                { default: () => '稍后查看' } // 按钮显示名称
              ),
              h(
                NButton,
                {
                  // 可在里面写按钮样式
                  type: 'primary',
                  size: 'small',
                  style:
                    'height: 32px; font-family: HarmonyOS Sans SC; background: #836FFF; font-size: 14px; color: #FFFFFF;',
                  onClick: () => {
                    lookBidDocumentDetail(data);
                    bidNotification.destroy();
                  } // 点击按钮后的回调
                },
                { default: () => '立即查看' } // 按钮显示名称
              )
            ]
          }
        )
    });
  }
}

// 行业类型(1.软件类 2.服务类 3.货物类 4.工程类 5.管理 6.设计 7.技术 8.经济类 20.其他)
const industryObj = ref({
  1: '软件类',
  2: '服务类',
  3: '货物类',
  4: '工程类',
  5: '管理类',
  6: '设计类',
  7: '技术类',
  8: '经济类',
  20: '其他'
});

// 查看标书详情
async function lookBidDocumentDetail(data: any) {
  const infoPath = [
    `项目名称：${data.title}`,
    `方案类型：${industryObj.value[data.industryType]}`,
    `采购单位：${data.tenderingUnit}`,
    `应标单位：${data.biddingUnit}`
  ];

  const pushParams: any = {
    generateType: 1,
    taskId: data.id,
    fileName: data.title,
    infoPath: infoPath.join(','),
    zhaoBiaoPath: data.more1,
    catalogPath: data.originalFilePath,
    isOneClickWrite: data.catalogDataStatus
  };
  await routerPushByKey('document_catalog', { query: pushParams });
}

function handleJump(index: any) {
  if (index == 3) {
    routerPushByKey('bid-materials', {
      query: {
        tab: '2'
      }
    });
  } else if (index == 2) {
    routerPushByKey('bid-materials', {
      query: {
        tab: '1'
      }
    });
  } else if (index == 1) {
    const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
    const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

    window.location.href = otherUrl.platformConsume;

    // window.location.href = 'http://192.168.7.22:28090/aiWeb/personCenter/consume';
    // window.location.href = "http://xiaoxiangzhiku.tvjoy.cn:28089/aiWeb/personCenter/consume";
  }
}
</script>

<template>
  <div class="background">
    <div class="home-container">
      <div class="title-img">
        <img src="@/assets/new-home/title.png" alt="" />
      </div>
      <div class="content">
        <div class="title">
          <span>{{ userInfo.user.companyName }}</span>
        </div>
        <div v-if="userIdentity == 2" class="tips">
          <img src="@/assets/new-home/vip-icon.png" alt="" />
          <span>VIP客户</span>
          <span>，{{ expireDate }}到期</span>
        </div>
        <div v-else class="tips">
          <img src="@/assets/new-home/common.png" alt="" />
          <span>试用客户</span>
          <span>，{{ expireDate }}到期</span>
        </div>
        <div class="box-area">
          <div class="box1" @click="handleJump(1)">
            <span class="box1-text">
              {{ usedCount }}
              <span class="unit">次</span>
            </span>
          </div>
          <div class="box2" @click="handleJump(2)">
            <span class="box2-text">
              {{ finishedBid }}
              <span class="unit">份</span>
            </span>
          </div>
          <div class="box3" @click="handleJump(3)">
            <span class="box3-text">
              {{ companyTotal }}
              <span class="unit">个</span>
            </span>
          </div>
        </div>
        <div class="btn" :class="[usedCount == 0 ? 'btn-gray' : '']" @click="createDocumentClick">
          <img src="@/assets/new-home/start.png" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.bg-layout {
  padding: 0 0 !important;
}
.background {
  .home-container {
    height: 100%;
    width: 100%;
    background: url('@/assets/new-home/bg2.png') no-repeat 0 -55px;
    background-size: cover;
    position: relative;
    .title-img {
      position: absolute;
      top: 12%;
      left: 4%;
      width: 31%;
      img {
        width: 100%;
      }
    }
    .content {
      position: absolute;
      top: 24%;
      left: 3.5%;
      width: 53%;
      height: 60%;
      .title {
        // left: 129px;
        // top: 219px;
        width: 100%;
        text-align: center;
        font-weight: 900;
        font-size: 2.6rem;
        color: #191919;
      }
      .tips {
        font-weight: 400;
        font-size: 1.3rem;
        color: #333333;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 0.5%;
        img {
          height: 2.5%;
          width: 2.5%;
          margin-right: 0.5%;
        }
      }
      .box-area {
        display: flex;
        justify-content: center;
        margin-top: 1%;
        width: 100%;
        height: 50%;
        .box1 {
          cursor: pointer;
          width: 33%;
          background-image: url('@/assets/new-home/left.png');
          background-repeat: no-repeat;
          background-size: contain;
          padding-top: 15%;
          padding-left: 6%;
          .box1-text {
            color: #6b5cf5;
            font-size: 2.3rem;

            font-weight: 900;
          }
        }
        .box2 {
          cursor: pointer;
          width: 33%;
          background-image: url('@/assets/new-home/done.png');
          background-repeat: no-repeat;
          background-size: contain;
          padding-top: 15%;
          padding-left: 6%;
          .box2-text {
            color: #22b4d1;
            font-size: 2.3rem;
            font-weight: 900;
          }
        }
        .box3 {
          cursor: pointer;
          width: 33%;
          background-image: url('@/assets/new-home/knowledge.png');
          background-repeat: no-repeat;
          background-size: contain;
          padding-top: 15%;
          padding-left: 6%;
          .box3-text {
            color: #4674f0;
            font-size: 2.3rem;
            font-weight: 900;
          }
        }
      }
      .unit {
        margin-left: 10px;
        font-weight: 900;
        font-size: 2rem;
        color: #27264d;
      }
      .btn {
        width: 43%;
        height: 13%;
        margin: 0 auto;
        cursor: pointer;
        img {
          margin-top: 1%;
          width: 100%;
        }
      }
      .btn-gray {
        filter: grayscale(1);
        cursor: default;
      }
    }

    :deep(.n-data-table .n-data-table-th) {
      background-color: #d9d3fe;
      height: 60px;
      color: #333333;
      font-size: 18px;
    }
    :deep(.n-data-table) {
      border-radius: 10px;
    }
  }
}
:deep(.n-notification-main-footer__action) {
  width: 100%;
}
</style>
